const jwt = require("jsonwebtoken");
// const crypto = require("./crypto.js")();
const fs = require("fs");
class Token{
    constructor(){
        // console.log("私钥： ", crypto.getRsakey() );
    }

    generateToken(data){
        var privateKey = fs.readFileSync("./cryptodir/rsa-private-key.pem");
        var token = jwt.sign(
            data,
            privateKey, 
            { 
                algorithm: 'RS256',
                expiresIn: 2 * 60  //120秒后失效
            });
        return token;
    }

    decodeToken( token ){
        var decoded = jwt.decode(token);
        console.log("decoded !!!!: ", decoded);
        return decoded;
    }

    verifyToken( token ){
       
        return new Promise( function(resolve , reject ){
             // verify a token asymmetric
            
            if( token == "null" ){
                
                reject({
                    refErr: "verifyToken",
                    err:{
                        
                        name:"token is null",
                        
                    }
                }
                );
                
                return ;
            }

            var cert = fs.readFileSync('./cryptodir/rsa-public-key.pem');  // get public key
            jwt.verify(token, cert, function(err, decoded) {
                
                if(err){
                    var decoded = jwt.decode(token, {complete: true});
                
                    if( !decoded.payload.user_id ){
                        reject({
                            refErr: "verifyToken",
                            err:{
                                
                                name:"userid of token is null",
                            }
                        })
                        return ;
                    }
                    reject({ refErr: "verifyToken", err , userId : decoded.payload.user_id });
                    return ;
                }
                resolve( decoded );
                
            });
        } );
       
    }
    //定义错误类型 --自定义
    checkErrorAboutVerifyToken( err ){
        console.log("@@err: ", err)
        if(err.refErr != "verifyToken"){
            return {
                refErr: "verifyTokenErr",
                status: 500,
                code: 500002,
                msg: "无效验证类型！！"
            }
        }
        switch( err.err.name ){
            case "TokenExpiredError": 
                //token 过期
                return {
                    refErr: "verifyTokenErr",
                    status: 400,
                    code: 400008,
                    msg: err.err.message
                };
            
            case "JsonWebTokenError": 
                //token校验不通过
                return {
                    refErr: "verifyTokenErr",
                    status: 400,
                    code: 400009,
                    msg: err.err.message
                };
            
            case "NotBeforeError": 
                return {
                    refErr: "verifyTokenErr",
                    status: 400,
                    code: 400010,
                    msg: err.err.message
                };
            case "token is null":
                return {
                    refErr: "verifyTokenErr",
                    status: 400,
                    code: 400013,
                    msg: "用户身份不存在 token null"
                };
            case "userid of token is null":
                return {
                    refErr: "verifyTokenErr",
                    status: 400,
                    code: 400013,
                    msg: "用户身份不存在 user id null"
                };
        }
    }

    checkExpireOfToken(){

    }

    destoryToken( id ){

    }

    saveToken( token ){

    }
}

//单例
let ProxyCreatToken = (function(){
    process.instanceToken = null;
    return function(){
        if(process.instanceToken){
            return process.instanceToken
        }
        return process.instanceToken = new Token();
    }
})();

module.exports = ProxyCreatToken();